# -*- coding: utf-8 -*-
import ast
import csv
import threading
import time
import pandas as pd
from tool.gongju import DuquRedis_HQ, GetProduct


class ZuidanCelue():
    """
    追单策略类
    self.sehzhi：格式为{'weituohou_k': 0, 'dsmcd_k': 10, 'weituojiaPL_k': 1, 'weituojiaPLJZ_k': 0, 'weituojiaPLJW_k': 2,
    'shifouchongfa_k': 1, 'chongfaJZ_k': 2, 'chongfaJZJW_k': 1, 'chongfaCS_k': 6, 'shifouchongfa2_k': 0,
    'fangancanshu_k': [5, 0, 1, 6, 0], 'zhenduicelue_k': 1, 'zhenduiheyue_k': 0, 'zhenduizhanghu_k': 1,
    'celuebiao_k': ['非本机', '手工下单', '交易助手撤单并追单'], 'heyuebiao_k': ['IF2108', 'IC2108', 'IH2108'],
    'zhanghubiao_k': ['122924'], 'weituohou_p': 0, 'dsmcd_p': 120, 'weituojiaPL_p': 1, 'weituojiaPLJZ_p': 0,
    'weituojiaPLJW_p': 2, 'shifouchongfa_p': 1, 'chongfaJZ_p': 2, 'chongfaJZJW_p': 1, 'chongfaCS_p': 8,
    'shifouchongfa2_p': 0, 'fangancanshu_p': [5, 0, 1, 6, 0], 'zhenduicelue_p': 1, 'zhenduiheyue_p': 0,
    'zhenduizhanghu_p': 1, 'celuebiao_p': ['非本机', '手工下单'], 'heyuebiao_p': ['IF2108', 'IC2108', 'IH2108'],
    'zhanghubiao_p': ['122924']}

    """
    def __init__(self):
        self.spi = None  # 账户实例列表
        self.zhanghuyubianhao = {}  # 账户对应编号字典
        self.shezhi = {}  # 设置字典
        self.tableWidget = None  # 为成交记录表，为qt tw
        self.jiaoyishijianbiao = {}
        self.__jiaoyishijiandaoru()  # 交易时间导入
        self.chedancishu = {}  # 撤单次数统计

    def __jiaoyishijiandaoru(self):
        """生成每个合约的交易时间表"""
        jyjl = pd.read_csv('name\\交易时间表.csv')
        for i in range(len(jyjl)):
            lsbl = ast.literal_eval(jyjl.jiaoyishijian.iat[i])
            self.jiaoyishijianbiao[jyjl.heyue.iat[i]] = lsbl

    def __jiaoyishijianpanduan(self, heyue):
        """判断是否是交易时间，是交易时间返回True"""
        heyuezhimu = GetProduct(heyue)
        jysj = self.jiaoyishijianbiao[heyuezhimu]
        bjsj = int(time.strftime("%H%M%S"))
        shifoumanzu = False
        for x in jysj:
            if bjsj > x[0] and bjsj < x[1]:
                shifoumanzu = True
        return shifoumanzu

    def dingshichedan(self):
        """
        固定时间测单并追单，定时撤单
        return: 撤单过的id
        """
        cheguodanid = []
        hangshu = self.tableWidget.rowCount()
        dangqianshijian = round(time.time())
        for i in range(hangshu):
            heyue = self.tableWidget.item(i, 2).text()
            if self.__jiaoyishijianpanduan(heyue):  # 在交易时间才进行撤单
                if self.tableWidget.item(i, 5).text() == "开仓":
                    if self.shezhi['weituohou_k']:  # 开启固定时间测单功能
                        if dangqianshijian - int(self.tableWidget.item(i, 12).text()) > self.shezhi['dsmcd_k']:
                            cdid = self.tableWidget.item(i, 3).text()
                            if cdid not in self.chedancishu:
                                self.chedancishu[cdid] = 0
                            if self.chedancishu[cdid] < self.shezhi['chongfaCS_k']:
                                zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                                self.spi[zhbh].cd_orders(cdid)  # 撤单
                                cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                                if self.shezhi['shifouchongfa_k']:
                                    if self.tableWidget.item(i, 4).text() == "买":
                                        mmfx = 1
                                    else:
                                            mmfx = -1
                                    kcsl = int(self.tableWidget.item(i, 7).text())
                                    scwtj = float(self.tableWidget.item(i, 9).text())
                                    self.__zhuidancelue_k(zhbh, heyue, mmfx, kcsl, cdid, scwtj)

                else:
                    if self.shezhi['weituohou_p']:  # 开启固定时间测单功能
                        if dangqianshijian - int(self.tableWidget.item(i, 12).text()) > self.shezhi['dsmcd_p']:
                            cdid = self.tableWidget.item(i, 3).text()
                            if cdid not in self.chedancishu:
                                self.chedancishu[cdid] = 0
                            if self.chedancishu[cdid] < self.shezhi['chongfaCS_p']:
                                zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                                self.spi[zhbh].cd_orders(cdid)
                                cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                                if self.shezhi['shifouchongfa_p']:
                                    if self.tableWidget.item(i, 4).text() == "买":
                                        mmfx = -1
                                    else:
                                        mmfx = 1
                                    kcsl = int(self.tableWidget.item(i, 7).text())
                                    scwtj = float(self.tableWidget.item(i, 9).text())
                                    self.__zhuidancelue_p(zhbh, heyue, mmfx, kcsl, cdid, scwtj)

        return cheguodanid

    def dingshichedan_lbcd加入平仓不足异常处理(self):
        """
        固定时间测单并追单，定时撤单，原版加入追单平仓不足异常
        return: 撤单过的id
        """
        cheguodanid = []
        hangshu = self.tableWidget.rowCount()
        dangqianshijian = round(time.time())
        for i in range(hangshu):
            heyue = self.tableWidget.item(i, 2).text()
            if self.__jiaoyishijianpanduan(heyue):  # 在交易时间才进行撤单
                # print("仓不足" not in self.tableWidget.item(i, 6).text(), self.tableWidget.item(i, 6).text())
                if "仓不足" not in self.tableWidget.item(i, 6).text():  # 平仓不足异常处理
                    if self.tableWidget.item(i, 5).text() == "开仓":
                        if self.shezhi['weituohou_k']:  # 开启固定时间测单功能
                            if dangqianshijian - int(self.tableWidget.item(i, 12).text()) > self.shezhi['dsmcd_k']:
                                cdid = self.tableWidget.item(i, 3).text()
                                if cdid not in self.chedancishu:
                                    self.chedancishu[cdid] = 0
                                if self.chedancishu[cdid] < self.shezhi['chongfaCS_k']:
                                    zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                                    self.spi[zhbh].cd_orders(cdid)  # 撤单
                                    cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                                    if self.shezhi['shifouchongfa_k']:
                                        if self.tableWidget.item(i, 4).text() == "买":
                                            mmfx = 1
                                        else:
                                                mmfx = -1
                                        kcsl = int(self.tableWidget.item(i, 7).text())
                                        scwtj = float(self.tableWidget.item(i, 9).text())
                                        self.__zhuidancelue_k(zhbh, heyue, mmfx, kcsl, cdid, scwtj)

                    else:
                        if self.shezhi['weituohou_p']:  # 开启固定时间测单功能
                            if dangqianshijian - int(self.tableWidget.item(i, 12).text()) > self.shezhi['dsmcd_p']:
                                cdid = self.tableWidget.item(i, 3).text()
                                if cdid not in self.chedancishu:
                                    self.chedancishu[cdid] = 0
                                if self.chedancishu[cdid] < self.shezhi['chongfaCS_p']:
                                    zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                                    self.spi[zhbh].cd_orders(cdid)
                                    cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                                    if self.shezhi['shifouchongfa_p']:
                                        if self.tableWidget.item(i, 4).text() == "买":
                                            mmfx = -1
                                        else:
                                            mmfx = 1
                                        kcsl = int(self.tableWidget.item(i, 7).text())
                                        scwtj = float(self.tableWidget.item(i, 9).text())
                                        self.__zhuidancelue_p(zhbh, heyue, mmfx, kcsl, cdid, scwtj)

                else:  # 平仓不足异常处理
                    zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                    cdid = self.tableWidget.item(i, 3).text()
                    if cdid not in self.chedancishu:
                        self.chedancishu[cdid] = 0
                    if self.chedancishu[cdid] < self.shezhi['chongfaCS_p']:
                        zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                        self.spi[zhbh].cd_orders(cdid)
                    cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                    if self.shezhi['shifouchongfa_p']:
                        if self.tableWidget.item(i, 4).text() == "买":
                            mmfx = 1
                        else:
                            mmfx = -1
                        kcsl = int(self.tableWidget.item(i, 7).text())
                        scwtj = float(self.tableWidget.item(i, 9).text())
                        self.__chuli_pingcangbuzu(zhbh, heyue, mmfx, kcsl, cdid, scwtj)

        return cheguodanid

    def jiagepianlichedan(self):
        """
        价格偏离撤单
        return: 撤单过的id
        """
        cheguodanid = []
        hangshu = self.tableWidget.rowCount()
        for i in range(hangshu):
            heyue = self.tableWidget.item(i, 2).text()
            if self.__jiaoyishijianpanduan(heyue):  # 在交易时间才进行撤单
                if self.tableWidget.item(i, 5).text() == "开仓":
                    if self.shezhi['weituojiaPL_k']:  # 开启固定时间测单功能
                        zxbddw = self.spi[0].get_zuixiaobiandong(heyue)
                        tick = DuquRedis_HQ(heyue)
                        if tick:
                            zuixinjia = float(tick['LastPrice'])  # 最新价跳
                        else:
                            print(heyue, " 无此合约价格,请订阅")
                            return
                        pianlijiawei = self.shezhi['weituojiaPLJW_k'] * zxbddw   # 偏离多少价位撤单
                        weituojia = float(self.tableWidget.item(i, 9).text())  # 委托价
                        if self.tableWidget.item(i, 4).text() == "买":
                            if zuixinjia - weituojia > pianlijiawei:
                                cdid = self.tableWidget.item(i, 3).text()
                                if cdid not in self.chedancishu:
                                    self.chedancishu[cdid] = 0
                                if self.chedancishu[cdid] < self.shezhi['chongfaCS_k']:
                                    zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                                    self.spi[zhbh].cd_orders(cdid)
                                    cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                                    if self.shezhi['shifouchongfa_k']:
                                        kcsl = int(self.tableWidget.item(i, 7).text())
                                        scwtj = float(self.tableWidget.item(i, 9).text())
                                        self.__zhuidancelue_k(zhbh, heyue, 1, kcsl, cdid, scwtj)
                        else:
                            if self.tableWidget.item(i, 4).text() == "卖":
                                if weituojia - zuixinjia > pianlijiawei:
                                    cdid = self.tableWidget.item(i, 3).text()
                                    if cdid not in self.chedancishu:
                                        self.chedancishu[cdid] = 0
                                    if self.chedancishu[cdid] < self.shezhi['chongfaCS_k']:
                                        zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                                        self.spi[zhbh].cd_orders(cdid)
                                        cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                                        if self.shezhi['shifouchongfa_k']:
                                            kcsl = int(self.tableWidget.item(i, 7).text())
                                            scwtj = float(self.tableWidget.item(i, 9).text())
                                            self.__zhuidancelue_k(zhbh, heyue, -1, kcsl, cdid, scwtj)
                else:
                    if self.shezhi['weituojiaPL_p']:  # 开启固定时间测单功能
                        zxbddw = self.spi[0].get_zuixiaobiandong(heyue)
                        tick = DuquRedis_HQ(heyue)
                        if tick:
                            zuixinjia = float(tick['LastPrice'])  # 最新价跳
                        else:
                            print(heyue, " 无此合约价格,请订阅")
                            return
                        pianlijiawei = self.shezhi['weituojiaPLJW_p'] * zxbddw   # 偏离多少价位撤单
                        weituojia = float(self.tableWidget.item(i, 9).text())  # 委托价
                        if self.tableWidget.item(i, 4).text() == "买":
                            if zuixinjia - weituojia > pianlijiawei:
                                cdid = self.tableWidget.item(i, 3).text()
                                if cdid not in self.chedancishu:
                                    self.chedancishu[cdid] = 0
                                if self.chedancishu[cdid] < self.shezhi['chongfaCS_p']:
                                    zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                                    self.spi[zhbh].cd_orders(cdid)
                                    cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                                    if self.shezhi['shifouchongfa_p']:
                                        kcsl = int(self.tableWidget.item(i, 7).text())
                                        scwtj = float(self.tableWidget.item(i, 9).text())
                                        self.__zhuidancelue_p(zhbh, heyue, -1, kcsl, cdid, scwtj)
                        else:
                            if self.tableWidget.item(i, 4).text() == "卖":
                                if weituojia - zuixinjia > pianlijiawei:
                                    cdid = self.tableWidget.item(i, 3).text()
                                    if cdid not in self.chedancishu:
                                        self.chedancishu[cdid] = 0
                                    if self.chedancishu[cdid] < self.shezhi['chongfaCS_p']:
                                        zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                                        self.spi[zhbh].cd_orders(cdid)
                                        cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                                        if self.shezhi['shifouchongfa_p']:
                                            kcsl = int(self.tableWidget.item(i, 7).text())
                                            scwtj = float(self.tableWidget.item(i, 9).text())
                                            self.__zhuidancelue_p(zhbh, heyue, 1, kcsl, cdid, scwtj)
        return cheguodanid

    def dingshichedan_xb(self):
        """
         定时撤单后条件是否追单，按条件追单，加入平仓不足异常处理
         return: 撤单过的id
         """
        cheguodanid = []
        hangshu = self.tableWidget.rowCount()
        dangqianshijian = round(time.time())
        for i in range(hangshu):
            heyue = self.tableWidget.item(i, 2).text()
            if self.__jiaoyishijianpanduan(heyue):  # 在交易时间才进行撤单
                if self.tableWidget.item(i, 5).text() == "开仓":
                    if self.shezhi['weituohou_k']:  # 开启固定时间测单功能
                        if dangqianshijian - int(self.tableWidget.item(i, 12).text()) > self.shezhi['dsmcd_k']:
                            cdid = self.tableWidget.item(i, 3).text()
                            if cdid not in self.chedancishu:  # 撤单次数初始化
                                self.chedancishu[cdid] = 0
                            if self.chedancishu[cdid] < self.shezhi['chongfaCS_k']:
                                # 价格如果超过吃亏价格不测单也不追单
                                baodanjia = float(self.tableWidget.item(i, 9).text())
                                zxbddw = self.spi[0].get_zuixiaobiandong(heyue) * 15
                                tick = DuquRedis_HQ(heyue)
                                if tick:
                                    zuixinjia = float(tick['LastPrice'])  # 最新价跳
                                else:
                                    print(heyue, " 无此合约价格,请订阅")
                                    return
                                if self.tableWidget.item(i, 4).text() == "买":
                                    if zuixinjia > baodanjia+zxbddw:
                                        self.chedancishu[cdid] += 1
                                        continue
                                else:
                                    if self.tableWidget.item(i, 4).text() == "卖":
                                        if zuixinjia < baodanjia - zxbddw:
                                            self.chedancishu[cdid] += 1
                                            continue

                                zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                                self.spi[zhbh].cd_orders(cdid)  # 撤单
                                # if cdid not in cheguodanid:
                                cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                                if self.shezhi['shifouchongfa_k']:
                                    if self.tableWidget.item(i, 4).text() == "买":
                                        mmfx = 1
                                    else:
                                        mmfx = -1
                                    kcsl = int(self.tableWidget.item(i, 7).text())
                                    scwtj = float(self.tableWidget.item(i, 9).text())
                                    self.__zhuidancelue_k(zhbh, heyue, mmfx, kcsl, cdid, scwtj)

                else:
                    if self.shezhi['weituohou_p']:  # 开启固定时间测单功能
                        if dangqianshijian - int(self.tableWidget.item(i, 12).text()) > self.shezhi['dsmcd_p']:
                            cdid = self.tableWidget.item(i, 3).text()
                            if cdid not in self.chedancishu:
                                self.chedancishu[cdid] = 0
                            if self.chedancishu[cdid] < self.shezhi['chongfaCS_p']:
                                # 价格如果超过吃亏价格不测单也不追单
                                baodanjia = float(self.tableWidget.item(i, 9).text())
                                zxbddw = self.spi[0].get_zuixiaobiandong(heyue) * 15
                                tick = DuquRedis_HQ(heyue)
                                if tick:
                                    zuixinjia = float(tick['LastPrice'])  # 最新价跳
                                else:
                                    print(heyue, " 无此合约价格,请订阅")
                                    return
                                if self.tableWidget.item(i, 4).text() == "买":
                                    if zuixinjia > baodanjia + zxbddw:
                                        self.chedancishu[cdid] += 1
                                        continue
                                else:
                                    if self.tableWidget.item(i, 4).text() == "卖":
                                        if zuixinjia < baodanjia - zxbddw:
                                            self.chedancishu[cdid] += 1
                                            continue

                                zhbh = self.zhanghuyubianhao[self.tableWidget.item(i, 0).text()]
                                self.spi[zhbh].cd_orders(cdid)
                                cheguodanid.append(cdid)  # 撤单ip返回给控制中心，用于删除此行
                                if self.shezhi['shifouchongfa_p']:
                                    if self.tableWidget.item(i, 4).text() == "买":
                                        mmfx = -1
                                    else:
                                        mmfx = 1
                                    kcsl = int(self.tableWidget.item(i, 7).text())
                                    scwtj = float(self.tableWidget.item(i, 9).text())
                                    self.__zhuidancelue_p(zhbh, heyue, mmfx, kcsl, cdid, scwtj)

        return cheguodanid

    def __xieru_csv(self, ulist):
        """
        追单记录写入本地文件
        :param ulist: 要写入的文件列表
        :return: 列表写入文件
        """
        with open('name\\zhuidanjilu\\' + time.strftime("%Y%m%d") + '.csv', "a", newline='',
                  encoding='gb2312') as file:
            writer = csv.writer(file, delimiter=',')
            writer.writerow(ulist)

    def __zhuidancelue_k(self, zhbh, kcbz, mmfx, kcsl, cdid, scwtj):
        """
        追单策略1，测单后直接追单，开仓，并将追单记录写入到csv
        :param zhbh: 要追单账户的编号
        :param kcbz: 合约
        :param mmfx: 买卖方向
        :param kcsl: 数量
        :param cdid: 测单的id
        :param scwtj: 上次委托价
        :return:
        """
        jiaoyishezhi = [zhbh, [1, 1], [88, 6, 1, 89], [kcbz], ['IF', 'IC'], ['celuecanshu'], '交易助追单', 1,
                        [self.shezhi['chongfaJZJW_k'], 0, 0, self.shezhi['chongfaJZ_k']], [0]]
        xdid = self.spi[zhbh].kc_orders(jiaoyishezhi, mmfx, kcsl)
        self.chedancishu[cdid] = self.chedancishu[cdid] + 1
        self.chedancishu[xdid] = self.chedancishu.pop(cdid)  # 替换原来的撤单id为下单id
        # 计算本次开仓的委托价格
        fangxiang2 = 1 if mmfx > 0 else 2
        if jiaoyishezhi[8][3] == 0:  # 为最新价
            kcjg = self.spi[zhbh].get_zuixinjia(kcbz)
        else:
            if jiaoyishezhi[8][3] == 1:  # 为对手价
                kcjg = self.spi[zhbh].get_duishoujia(kcbz, fangxiang2)
            else:
                if jiaoyishezhi[8][3] == 2:  # 为排队价
                    kcjg = self.spi[zhbh].get_paiduijia(kcbz, fangxiang2)
                else:
                    kcjg = jiaoyishezhi[8][3]
        if kcjg:  # 没获取到价格，返回为0
            zxbddw = self.spi[0].get_zuixiaobiandong(kcbz)
            kcjg = kcjg + jiaoyishezhi[8][0] * zxbddw if mmfx > 0 else kcjg - jiaoyishezhi[8][0] * zxbddw  # 加减委托偏移后的价格
            huadian = kcjg - scwtj if mmfx > 0 else scwtj - kcjg
            huadian = huadian * kcsl
        else:
            huadian = 0
        ulist = [self.spi[zhbh].UserID, self.spi[zhbh].bieming, kcbz, xdid, self.chedancishu[xdid], mmfx,
                 '开', kcsl, kcjg, scwtj, huadian, time.strftime("%H%M%S")]
        self.__xieru_csv(ulist)
        # print(self.chedancishu[xdid])

    def __zhuidancelue_p(self, zhbh, kcbz, mmfx, kcsl, cdid, scwtj):
        """
        追单策略1，测单后直接追单，平仓，并将追单记录写入到csv
        :param zhbh: 要追单账户的编号
        :param kcbz: 合约
        :param mmfx: 买卖方向
        :param kcsl: 数量
        :param cdid: 测单的id
        :param scwtj: 上次委托价
        :return:
        """
        jiaoyishezhi = [zhbh, [1, 1], [88, 6, 1, 89], [kcbz], ['IF', 'IC'], ['celuecanshu'], '交易助追单', 1,
                        [self.shezhi['chongfaJZJW_p'], 0, 0, self.shezhi['chongfaJZ_p']], [0]]

        def yanshi_pc():
            time.sleep(0.3)
            xdid = self.spi[zhbh].pc_orders(jiaoyishezhi, mmfx, kcsl)
            self.chedancishu[cdid] = self.chedancishu[cdid] + 1
            self.chedancishu[xdid] = self.chedancishu.pop(cdid)  # 替换原来的撤单id为下单id
            # print('平=', self.chedancishu[xdid])
            # 计算本次开仓的委托价格
            fangxiang2 = 1 if mmfx > 0 else 2
            if jiaoyishezhi[8][3] == 0:  # 为最新价
                kcjg = self.spi[zhbh].get_zuixinjia(kcbz)
            else:
                if jiaoyishezhi[8][3] == 1:  # 为对手价
                    kcjg = self.spi[zhbh].get_duishoujia(kcbz, fangxiang2)
                else:
                    if jiaoyishezhi[8][3] == 2:  # 为排队价
                        kcjg = self.spi[zhbh].get_paiduijia(kcbz, fangxiang2)
                    else:
                        kcjg = jiaoyishezhi[8][3]
            if kcjg:  # 没获取到价格，返回为0
                zxbddw = self.spi[0].get_zuixiaobiandong(kcbz)
                kcjg = kcjg - jiaoyishezhi[8][0] * zxbddw if mmfx > 0 else kcjg + jiaoyishezhi[8][0] * zxbddw  # 加减委托偏移后的价格
                huadian = scwtj-kcjg if mmfx > 0 else kcjg - scwtj
                huadian = huadian*kcsl
            else:
                huadian = 0
            ulist = [self.spi[zhbh].UserID, self.spi[zhbh].bieming, kcbz, xdid, self.chedancishu[xdid], mmfx,
                     '平', kcsl, kcjg, scwtj, huadian, time.strftime("%H%M%S")]
            self.__xieru_csv(ulist)

        threading.Thread(target=yanshi_pc, args=()).start()

    def __chuli_pingcangbuzu(self, zhbh, kcbz, mmfx, kcsl, cdid, scwtj):
        """
        处理平仓不足错误，开仓，并将追单记录写入到csv
        :param zhbh: 要追单账户的编号
        :param kcbz: 合约
        :param mmfx: 买卖方向
        :param kcsl: 数量
        :param cdid: 测单的id
        :param scwtj: 上次委托价
        :return:
        """

        jiaoyishezhi = [zhbh, [1, 1], [88, 6, 1, 89], [kcbz], ['IF', 'IC'], ['celuecanshu'], '交易助追单', 1,
                        [self.shezhi['chongfaJZJW_k'], 0, 0, self.shezhi['chongfaJZ_k']], [0]]
        xdid = self.spi[zhbh].kc_orders(jiaoyishezhi, mmfx, kcsl)

        self.chedancishu[cdid] = self.chedancishu[cdid] + 1
        self.chedancishu[xdid] = self.chedancishu.pop(cdid)  # 替换原来的撤单id为下单id
        # 计算本次开仓的委托价格
        fangxiang2 = 1 if mmfx > 0 else 2
        if jiaoyishezhi[8][3] == 0:  # 为最新价
            kcjg = self.spi[zhbh].get_zuixinjia(kcbz)
        else:
            if jiaoyishezhi[8][3] == 1:  # 为对手价
                kcjg = self.spi[zhbh].get_duishoujia(kcbz, fangxiang2)
            else:
                if jiaoyishezhi[8][3] == 2:  # 为排队价
                    kcjg = self.spi[zhbh].get_paiduijia(kcbz, fangxiang2)
                else:
                    kcjg = jiaoyishezhi[8][3]
        if kcjg:  # 没获取到价格，返回为0
            zxbddw = self.spi[0].get_zuixiaobiandong(kcbz)
            kcjg = kcjg + jiaoyishezhi[8][0] * zxbddw if mmfx > 0 else kcjg - jiaoyishezhi[8][0] * zxbddw  # 加减委托偏移后的价格
            huadian = kcjg - scwtj if mmfx > 0 else scwtj - kcjg
            huadian = huadian * kcsl
        else:
            huadian = 0
        ulist = [self.spi[zhbh].UserID, self.spi[zhbh].bieming, kcbz, xdid, self.chedancishu[xdid], mmfx,
                 '开', kcsl, kcjg, scwtj, huadian, time.strftime("%H%M%S")]
        self.__xieru_csv(ulist)
        # print(self.chedancishu[xdid])

    #  编写自己的追单策略，可以参照上面的普通追单例子写
    def zidingyizhuidancelue_k(self):
        """自定义追单策略，开仓，每隔一秒此方法会被追单主程序条用一次"""
        if self.shezhi['shifouchongfa2_k']:  # 是否重发2,分配发单策略
            pass

    def zidingyizhuidancelue_p(self):
        """自定义追单策略，平仓，，每隔一秒此方法会被追单主程序条用一次"""
        if self.shezhi['shifouchongfa2_p']:  # 是否重发2,分配发单策略
            pass

